package com.vcc.boss.controller;


import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckPermission;
import com.vcc.core.annotations.RepeatSubmit;
import com.vcc.core.annotations.RestPack;
import com.vcc.core.exception.ProgramException;
import com.vcc.core.util.RedisCustomizeUtils;
import com.vcc.data.entity.ClientPermission;
import com.vcc.data.entity.ClientRolePermission;
import com.vcc.data.entity.Role;
import com.vcc.service.boss.request.clientPermission.BossClientPermissionCreateRequest;
import com.vcc.service.boss.request.clientPermission.BossClientPermissionCheckedUpdateRequest;
import com.vcc.service.boss.response.clientRole.ClientPermissionVoBoss;
import com.vcc.service.service.ClientPermissionService;
import com.vcc.service.service.ClientRolePermissionService;
import com.vcc.service.service.RoleService;
import com.vcc.service.service.UserRoleService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/client/permission")
public class ClientPermissionController {

    @Resource
    private ClientPermissionService clientPermissionService;

    @Resource
    private ClientRolePermissionService clientRolePermissionService;
    @Resource
    private RoleService roleService;
    @Autowired
    private UserRoleService userRoleService;


    @RestPack
    @SaCheckPermission(value = "client:permission:list:view")
    @SaCheckLogin
    @GetMapping("/list")
    public List<ClientPermissionVoBoss> list() {
        List<ClientPermission> clientPermissions = clientPermissionService.list();
        //根据父子关系进行分组
        ArrayList<ClientPermissionVoBoss> clientPermissionVos = new ArrayList<>();
        List<ClientPermission> parentId = clientPermissions.stream().filter(ClientPermission::getHasParent).toList();
        for (ClientPermission clientPermission : parentId) {
            ClientPermissionVoBoss clientPermissionVo = new ClientPermissionVoBoss(clientPermission);
            List<ClientPermissionVoBoss> children = clientPermissions
                    .stream()
                    .filter(it -> it.getParentId().equals(clientPermission.getId()))
                    .map(ClientPermissionVoBoss::new)
                    .toList();
            clientPermissionVo.setChildren(children);
            clientPermissionVos.add(clientPermissionVo);
        }
        return clientPermissionVos;
    }


    @RestPack
    @SaCheckPermission(value = "client:permission:list:create")
    @PostMapping("/add")
    @RepeatSubmit
    public Boolean add(@RequestBody BossClientPermissionCreateRequest bossClientPermissionCreateRequest) {
        if (clientPermissionService.existsByCode(bossClientPermissionCreateRequest.getCode())) {
            throw new ProgramException("权限编码已存在");
        }
        if (clientPermissionService.existsByName(bossClientPermissionCreateRequest.getName())) {
            throw new ProgramException("权限名称已存在");
        }
        ClientPermission clientPermission = new ClientPermission();
        clientPermission.setCode(bossClientPermissionCreateRequest.getCode());
        clientPermission.setName(bossClientPermissionCreateRequest.getName());
        clientPermission.setHasParent(bossClientPermissionCreateRequest.getHasParent());
        clientPermission.setParentId(bossClientPermissionCreateRequest.getHasParent() ? 0L : bossClientPermissionCreateRequest.getParentId());
        clientPermissionService.save(clientPermission);
        //获取初始角色代码
        Role clientInitRole = roleService.getClientInitRole();
        if (clientInitRole == null) {
            throw new ProgramException("初始角色不存在，请先设置初始角色");
        }
        List<Role> roles = roleService.listByCode(clientInitRole.getCode());
        clientRolePermissionService.deleteByRoleIdsAndPermissionId(
                clientPermission.getId(),
                roles.stream().map(Role::getId).toList()
        );
        for (Role role : roles) {
            ClientRolePermission clientRolePermission = new ClientRolePermission();
            clientRolePermission.setRoleId(role.getId());
            clientRolePermission.setPermissionId(clientPermission.getId());
            clientRolePermission.setStatus(0);
            clientRolePermissionService.save(clientRolePermission);
        }
        RedisCustomizeUtils.removePrefixKey("user_client_permission:");
        return true;
    }


    @RestPack
    @SaCheckPermission(value = "client:permission:list:edit")
    @PostMapping("/updateChecked")
    @RepeatSubmit
    public Boolean updateChecked(@RequestBody @Validated BossClientPermissionCheckedUpdateRequest bossClientPermissionCheckedUpdateRequest) {
        ClientPermission clientPermission = clientPermissionService.getById(bossClientPermissionCheckedUpdateRequest.getId());
        if (clientPermission == null) {
            throw new ProgramException("权限不存在");
        }
        if (clientPermission.getHasClientChecked() != null && clientPermission.getHasClientChecked().equals(bossClientPermissionCheckedUpdateRequest.getHasClientChecked())) {
            throw new ProgramException("权限状态未发生变化");
        }
        if (clientPermission.getHasParent()) {
            clientPermissionService.updateHasCheckedIdByParentId(bossClientPermissionCheckedUpdateRequest.getId(), bossClientPermissionCheckedUpdateRequest.getHasClientChecked());
        } else {
            clientPermissionService.updateHasCheckedId(bossClientPermissionCheckedUpdateRequest.getId(), bossClientPermissionCheckedUpdateRequest.getHasClientChecked());
        }
        if (!bossClientPermissionCheckedUpdateRequest.getHasClientChecked()) {
            clientRolePermissionService.deleteByPermissionId(bossClientPermissionCheckedUpdateRequest.getId());
        } else {
            //获取初始角色代码
            Role clientInitRole = roleService.getClientInitRole();
            if (clientInitRole == null) {
                throw new ProgramException("初始角色不存在，请先设置初始角色");
            }
            List<Role> roles = roleService.listByCode(clientInitRole.getCode());
            clientRolePermissionService.deleteByRoleIdsAndPermissionId(
                    bossClientPermissionCheckedUpdateRequest.getId(),
                    roles.stream().map(Role::getId).toList()
            );
            for (Role role : roles) {
                ClientRolePermission clientRolePermission = new ClientRolePermission();
                clientRolePermission.setRoleId(role.getId());
                clientRolePermission.setPermissionId(bossClientPermissionCheckedUpdateRequest.getId());
                clientRolePermission.setStatus(0);
                clientRolePermissionService.save(clientRolePermission);
            }
        }
        RedisCustomizeUtils.removePrefixKey("user_client_permission:");
        return true;
    }
}
